package ui;

import java.awt.AWTException;
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.TrayIcon.MessageType;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.ScrollPaneConstants;
import javax.swing.UIManager;
import javax.swing.border.EtchedBorder;
import javax.swing.plaf.basic.BasicInternalFrameTitlePane.SystemMenuBar;

import com.sun.servicetag.SystemEnvironment;

import network.NetworkVars;
import core.Phrox;

public class Gui extends JFrame implements ActionListener, KeyListener, WindowListener, GuiPlugin{

//*
	public static void main(String[] args){
		System.out.println("Testing System Tray Icon");
		Gui g = new Gui("Sys Tray icon test");
		g.gui_display(true);
		//*
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {}
		//*/
		System.out.println("Getting focus");
		g.chat_AddText("JEX: Hello everyone, howe are all of you? I'm good. :)");
	}
//*/
	public static final String thumbNail = Phrox.fD+"res"+Phrox.fD+"PhroxThumb.JPG";
		
	private TrayIcon trayIc;
	
	private Container pane = this.getContentPane();
	private JButton sendButton;
	private JTextArea conversationArea;
	private JTextField messageText;
	private JScrollPane scrollPane;
	public JLabel userThisName;
	private boolean closed = false;
	
	public Gui(){
		this("");
	}

	public Gui(String title){
		
		//*			
		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (Exception e1) {
			e1.printStackTrace();
		}//doesn't really matter if any of the exceptions are thrown, the default look and feel doesn't matter
		//*/
		
		setTitle(title);
		String iconPath =Phrox.rootDir+thumbNail;
		System.out.println("Thumb Nail:"+iconPath);
		ImageIcon i = new ImageIcon(iconPath);
		setIconImage(i.getImage());
				
		Container c = getContentPane();
		c.setLayout(null);
		setSize(550, 480);
		
		//menu:
		
		JMenuBar menuBar;
		JMenu menu;
		JMenuItem menuItem;
		JCheckBoxMenuItem cbMenuItem;
		
		//Create the menu bar.
		menuBar = new JMenuBar();
		
		menu = new JMenu("Menu");
		menu.setMnemonic(KeyEvent.VK_A);
		menu.getAccessibleContext().setAccessibleDescription(
		        "The only menu in this program that has menu items");
		menuBar.add(menu);

		
		cbMenuItem = new JCheckBoxMenuItem("Mute sound");
		cbMenuItem.addActionListener(this);
		cbMenuItem.setAccelerator( KeyStroke.getKeyStroke( KeyEvent.VK_M, ActionEvent.CTRL_MASK));
		menu.add(cbMenuItem);

		//menu.addSeparator();
		
		menuItem = new JMenuItem("Update", KeyEvent.VK_U);
		menuItem.addActionListener(this);
		menuItem.setAccelerator( KeyStroke.getKeyStroke( KeyEvent.VK_U, ActionEvent.CTRL_MASK));
		menuItem.getAccessibleContext().setAccessibleDescription("Updates Phrox");
		menu.add(menuItem);
		
		cbMenuItem = new JCheckBoxMenuItem("Remember Server");
		cbMenuItem.addActionListener(this);
		cbMenuItem.setAccelerator( KeyStroke.getKeyStroke( KeyEvent.VK_S, ActionEvent.CTRL_MASK));
		cbMenuItem.getAccessibleContext().setAccessibleDescription("Updates Phrox");
		try {
			cbMenuItem.setSelected(Phrox.getRemServer());
		} catch (Exception e) {}
		menu.add(cbMenuItem);
		
		menu.addSeparator();
		
		menuItem = new JMenuItem("About", KeyEvent.VK_A);
		menuItem.addActionListener(this);
		menuItem.getAccessibleContext().setAccessibleDescription("Info about Phrox");
		menu.add(menuItem);
		
		
		
		//a group of JMenuItems
		
		
		menuItem = new JMenuItem("Quit", KeyEvent.VK_Q);
		menuItem.addActionListener(this);
		menuItem.setAccelerator( KeyStroke.getKeyStroke( KeyEvent.VK_Q, ActionEvent.CTRL_MASK));
		menuItem.getAccessibleContext().setAccessibleDescription("Exits Phrox");
		menu.add(menuItem);
		
		setJMenuBar(menuBar);
		//*
		if(SystemTray.isSupported()){
			System.out.println("System Tray is supported");
			SystemTray sys = SystemTray.getSystemTray();
			try {
				PopupMenu pm = new PopupMenu();
				MenuItem m1 = new MenuItem("About");
				m1.addActionListener(this);
				pm.add(m1);
				m1 = new MenuItem("Quit");
				m1.addActionListener(this);
				pm.add(m1);
				trayIc = new TrayIcon(i.getImage(),"Phrox Chat",pm);
				sys.add(trayIc);
			} catch (AWTException e) {
				trayIc = null;
			}
			System.out.println(SystemMenuBar.getDefaultLocale().getDisplayName());
		}
		//*/
		
		//rest of the GUI
		conversationArea = new JTextArea();
		conversationArea.setBounds(15, 31, 500, 317);
		conversationArea.setEditable(false);
		conversationArea.setWrapStyleWord(true);
		conversationArea.setLineWrap(true);
		conversationArea.setAutoscrolls(true);
		conversationArea.setFont(new Font("Tahoma", Font.PLAIN, 12));
		pane.add(conversationArea);
		
		
		scrollPane = new JScrollPane(conversationArea);
		scrollPane.setBounds(15, 31, 500, 317);
		scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
		
		//scrollPane.setAutoscrolls(true);
		
		pane.add(scrollPane);
		
		JLabel messageConvoSeparator = new JLabel("Type a message to send below:");
		messageConvoSeparator.setBounds(15, 360, 500, 20);
		pane.add(messageConvoSeparator);
		
		messageText = new JTextField("");
		messageText.setBounds(15, 385, 412, 23);
		messageText.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));
		messageText.addActionListener(this);
		messageText.addKeyListener(this);
		pane.add(messageText);
		
		sendButton = new JButton("Send");
		sendButton.setBounds(440, 385, 75, 23);
		sendButton.addActionListener(this);
		pane.add(sendButton);
		
		//*		
		userThisName = new JLabel("You are: "+NetworkVars.localUsr.getName());
		userThisName.setAlignmentX(JLabel.CENTER);
		userThisName.setBounds(15, 3, 200, 23);
		pane.add(userThisName);
		//*/
		
				
		setContentPane(pane);
		setResizable(false);
		//setVisible(true);
		setDefaultCloseOperation(DISPOSE_ON_CLOSE);

		this.addWindowListener(this);

		
	}

	//@Override
	public void chat_AddText(String str){
		String t = conversationArea.getText();
		conversationArea.setText(t+str);
		
		conversationArea.setCaretPosition(conversationArea.getText().length());
		//
		//*
		if(!isFocused()){
			trayIc.displayMessage("", str.substring(0,Math.min(str.indexOf(":"), 15))+" said something", MessageType.NONE);
		}
		//*/
		
	}

	//@Override
	public void chat_ClearText(){
		conversationArea.setText("");
	}
	
	public String chat_getText(){
		return conversationArea.getText();
	}
	
	//@Override
	public String type_GetText(){
		String send = out;
		out = null;
		hasText=false;
		return send;
	}
	
	//@Override
	public boolean type_hasText(){
		return hasText;
	}

	//@Override
	public void type_SetText(String s){
		if(messageText.getText().replace(" ", "").replace("\t", "").length() <= 1){
			messageText.setText(s);
		}
	}
	
	//@Override
	public void userName_SetText(String str){
		userThisName.setText(str);
	}
	
	//@Override
	/**
	 * added for plug in reasons
	 */
	public void gui_dispose(){
		this.dispose();
	}
	
	public void gui_display(boolean b){
		this.setVisible(b);
	}
	
	
	//@Override
	public void gui_setTitle(String str){
		setTitle(str);
	}
	
	//@Override
	public boolean gui_displayable(){
		return !closed;
	}
	
	@Override
	public void gui_hasLag(byte b) {
		//draw outline regardless
		try {
			Graphics tmp = this.getGraphics();
			
			if(1 == b){
				tmp.setColor(Color.RED);
			}else if (0 == b){
				tmp.setColor(Color.GREEN);
			}else if(-1 == b){
				tmp.setColor(this.getBackground());
			}
			tmp.fillOval(520, 60, 22, 22);
		} catch (Exception e) {
			System.out.println("Error Drawning Lag Circle");
		}
		
	}

	
	
	private String out = null;
	private boolean hasText=false;
	
	
	//@Override
	public void actionPerformed(ActionEvent e) {
		//System.out.println(e.getActionCommand());
		if(e.getActionCommand().equals("Send")){
			//send the text
			if(messageText.getText().replace("\n", "").replace(" ", "").length() > 0){
				out = messageText.getText();
				hasText=true;
			}
			messageText.setText("");
		}else if(e.getActionCommand().equalsIgnoreCase("Quit")){
			//close gui
			closed = true;
			this.dispose();
		}else if(e.getActionCommand().equalsIgnoreCase("Mute sound")){
			//mute sound
			Phrox.setSoundMute( ((JCheckBoxMenuItem)e.getSource()).isSelected() );
			
		}else if(e.getActionCommand().equalsIgnoreCase("Update")){
			//check for update
			
			Thread updateThread = new Thread(){
				public void run(){
					Phrox.checkUpdate(true);
				}
			};
			updateThread.setDaemon(true);
			updateThread.start();
			
		}else if(e.getActionCommand().equalsIgnoreCase("About")){

			new PopUp(Phrox.name+" "+Phrox.version+" - Info",Phrox.p_ShortInfo());
			
		}else if(e.getActionCommand().equalsIgnoreCase("Remember Server")){
			//System.out.println(((JCheckBoxMenuItem)e.getSource()).isSelected());
			Phrox.setRemServer(((JCheckBoxMenuItem)e.getSource()).isSelected());
		}
		
	}

	//@Override
	public void keyPressed(KeyEvent e) {}

	//@Override
	public void keyReleased(KeyEvent e) {}

	//@Override
	public void keyTyped(KeyEvent e) {
		//System.out.println(e.getKeyChar());
		//System.out.println(e.getKeyCode());
		//System.out.println(e.getModifiers());
		if(e.getKeyChar() == '\n' && e.getModifiers() <= 0){
			
			out = messageText.getText();
			out = out.replace("\n", "");
			messageText.setText("");
			hasText=true;
		}
	}


	//@Override
	public void windowClosed(WindowEvent e) {
		System.out.println("CLOSED");
		Phrox.exit = true;
		closed = true;
	}


	//@Override
	public void windowClosing(WindowEvent e) {
		System.out.println("CLOSING");
		System.out.println(this.gui_displayable());
		Phrox.exit = true;
		//cheating, your not allowed to call this from custom Guis.
		closed = true;
	}
	
	//@Override
	public void windowActivated(WindowEvent e) {}


	//@Override
	public void windowDeactivated(WindowEvent e) {}


	//@Override
	public void windowDeiconified(WindowEvent e) {}


	//@Override
	public void windowIconified(WindowEvent e) {}


	//@Override
	public void windowOpened(WindowEvent e) {}
	
	
}
